//
//  MoreItemController.swift
//  ShiZhe
//
//  Created by 陈卿伟 on 16/9/7.
//  Copyright © 2016年 陈卿伟. All rights reserved.
//

import UIKit
import Alamofire
import SwiftyJSON

class MoreItemController: MainViewController {
    
    
    //已关注的item
    var concernItemName:Array<String> = []
    var concernItemID:Array<String> = []
    
    var tableView:LeftTableView!
    var cell:LeftCell!
    var collectionView:RightCollectionView!
    var menuModel:MenuModelH!
    var selecterRow = 0

    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "标签选择"
        self.menuModel = MenuModelH(menu: [], selecte1: 1)
        self.getAlreadyMenuAlamofire()
        self.getMenuAlamofire()
        self.addTableViewToController()
        self.addCollectionViewToControll()
    }
}

//MARK:--UI
extension MoreItemController{
    //添加tableView进来
    func addTableViewToController(){
        tableView = LeftTableView(frame: CGRect(x: 0, y: 0, width: 88*SCALEW, height: HeightAPP), style: .Grouped)
        tableView.delegate = self
        tableView.dataSource = self
        self.view.addSubview(tableView)
    }
    
    //添加collectionview进来
    func addCollectionViewToControll(){
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSize(width: 82*SCALEW, height: 40*SCALEH)
        layout.scrollDirection = .Vertical
        
        collectionView = RightCollectionView(frame: CGRect(x: 88*SCALEW, y: 0, width: WidthAPP-88*SCALEW, height: HeightAPP-64*SCALEH), collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.registerClass(RightCell.self, forCellWithReuseIdentifier: "rightCell")
        collectionView.registerClass(RightHeadView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "rightHeader")
        collectionView.registerClass(RightFootView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionFooter, withReuseIdentifier: "rightFooter")
        self.view.addSubview(collectionView)
    }
}


//MARK:--tableView  delegate  datasource
extension MoreItemController:UITableViewDelegate,UITableViewDataSource{
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        
        return 1
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return menuModel.count1+1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        cell = LeftCell(style: .Default, reuseIdentifier: "moreItemLeftCell")
        tableView.selectRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0), animated: true, scrollPosition: .None)
        if indexPath.row == 0{
            cell.cellLabel.text = "已关注"
        }else{
            cell.cellLabel.text = menuModel.menuName1[indexPath.row-1]
        }
        return cell
    }
    
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        self.selecterRow = indexPath.row
        if selecterRow != 0{
            menuModel.selecte1 = indexPath.row
            menuModel.deleteMenu()
            menuModel.getMenuItemCount()
            self.collectionView.reloadData()
        }else{
            self.concernItemName = []
            self.concernItemID = []
            self.getAlreadyMenuAlamofire()
        }
        self.collectionView.scrollRectToVisible(CGRect(x: 88*SCALEW, y: 0, width: WidthAPP-88*SCALEW, height: HeightAPP-64*SCALEH), animated: true)
    }
}

//MARK:--collectionView  delegate  datasource
extension MoreItemController:UICollectionViewDelegateFlowLayout,UICollectionViewDelegate,UICollectionViewDataSource{
    
    
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        if selecterRow == 0{
            return 1
        }else{
            return menuModel.count2
        }
        
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if selecterRow == 0{
            return concernItemName.count
        }else{
            return menuModel.menuName3[section].count
        }
    }
    
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let item = collectionView.dequeueReusableCellWithReuseIdentifier("rightCell", forIndexPath: indexPath) as! RightCell
        if selecterRow == 0{
            item.titleLabel.text = concernItemName[indexPath.row]
            item.selected = true
        }else{
            let muneName = menuModel.menuName3[indexPath.section][indexPath.row]
            item.titleLabel.text = muneName
            for itemName in self.concernItemName{
                if itemName == muneName{
                    item.selected = true
                }
            }
        }
        return item
    }
    
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
        return UIEdgeInsetsMake(0.1, 10, 0.1, 10)
    }
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
        return CGSize(width: WidthAPP, height: 52*SCALEH)
    }
    
    
    func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
        return CGSize(width: WidthAPP, height: 20*SCALEH)
    }
    
    func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
        let kindView = UICollectionReusableView()
        switch kind {
        case UICollectionElementKindSectionHeader:
            let headerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "rightHeader", forIndexPath: indexPath) as! RightHeadView
            if selecterRow == 0{
                headerView.titleLabel.text = "单机删除已关注标签"
            }else{
                headerView.titleLabel.text = menuModel.menuName2[indexPath.section]
            }
            
            return headerView
        case UICollectionElementKindSectionFooter:
            let footerView = collectionView.dequeueReusableSupplementaryViewOfKind(kind, withReuseIdentifier: "rightFooter", forIndexPath: indexPath) as! RightFootView
            return footerView
        default:
            return kindView
        }
    }
    
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let item = self.collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: indexPath.row, inSection: indexPath.section)) as! RightCell
        if selecterRow == 0{
            let menuID = self.concernItemID[indexPath.row]
            self.deleteItemAlamofire(menuID,item:item)
            item.userInteractionEnabled = false
        }else{
            let muneName = menuModel.menuName3[indexPath.section][indexPath.row]
            var count:Int = 0
            if self.concernItemName.count != 0{
                print(self.concernItemName)
                for itemName in self.concernItemName{
                    if itemName != muneName{
                        count += 1
                    }
                    if count == self.concernItemName.count{
                        item.indicator.startAnimating()
                        let menuID = menuModel.menuID3[indexPath.section][indexPath.row]
                        self.postMenuIDAlamofire(menuID,menu_name: muneName,item: item)
                    }
                }
            }else{
                item.indicator.startAnimating()
                let menuID = menuModel.menuID3[indexPath.section][indexPath.row]
                self.postMenuIDAlamofire(menuID,menu_name: muneName,item: item)
            }
        }
    }
}

//MARK:--Alamofire
extension MoreItemController{
    //得到menu
    func getMenuAlamofire(){
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu").responseJSON { (data) in
            let json = JSON(data: data.data!).arrayValue
            self.menuModel = MenuModelH(menu: json, selecte1: 1)
            self.menuModel.getMenuItemCount()
            dispatch_async(dispatch_get_main_queue(), { 
                self.tableView.reloadData()
                self.collectionView.reloadData()
            })
        }
    }
    
    //得到已经关注的menu
    func getAlreadyMenuAlamofire(){
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu/get_user_menu", headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!).arrayValue
            for i in 0..<json.count{
                let menu_id = json[i]["menu_id"].stringValue
                let menu_name = json[i]["menu_name"].stringValue
                self.concernItemName.insert(menu_name, atIndex: i)
                self.concernItemID.insert(menu_id, atIndex: i)
            }
            dispatch_async(dispatch_get_main_queue(), {
                self.collectionView.reloadData()
            })
        }
    }
    
    //给服务器传送menuId
    func postMenuIDAlamofire(menu_id:String,menu_name:String,item:RightCell){
        let parameters = ["menu_id":menu_id]
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu/in_menu", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!)
            print(json)
            dispatch_async(dispatch_get_main_queue(), {
                item.indicator.stopAnimating()
                self.concernItemName.insert(menu_name, atIndex: self.concernItemName.count)
                self.concernItemID.insert(menu_id, atIndex: self.concernItemID.count)
                self.collectionView.reloadData()
            })
        }
    }
    
    //删除已关注的item项
    func deleteItemAlamofire(menu_id:String,item:RightCell){
        let parameters = ["menu_id":menu_id]
        let headers = ["token":OperateUserDefaults.takeUserInfo().token]
        Alamofire.request(.POST, "http://srxapp.zhekd.com/ios.php/Menu/dele_menu", parameters: parameters, encoding: .JSON, headers: headers).responseJSON { (data) in
            let json = JSON(data: data.data!)
            print(json)
            dispatch_async(dispatch_get_main_queue(), {
                item.userInteractionEnabled = true
                self.concernItemName = []
                self.concernItemID = []
                self.getAlreadyMenuAlamofire()
            })
        }
    }
    
}














